<template>
  <div>
    <div class="title">退包装物</div>
    <div style="margin-top: 20px;">
      <el-space>
<!--        <el-button @click="doSearch">查询</el-button>-->
        <div style="height: 30px;font-size: 18px;color: #515A6E;">日期：</div>
        <div style="height: 30px;font-size: 16px;color: #515A6E;">
          <JPicker size="default" v-model="billDate" />
        </div>
        <div style="height: 30px;font-size: 18px;color: #515A6E;margin-left: 50px;">客户：</div>
        <div style="height: 30px;font-size: 16px;color: #515A6E;border-bottom: 1px solid rgba(0,0,0,0.2);min-width: 300px;">
          {{ buName }}
        </div>
        <div style="height: 30px;font-size: 18px;color: #515A6E;margin-left: 50px;">地址：</div>
        <div style="height: 30px;font-size: 16px;color: #515A6E;border-bottom: 1px solid rgba(0,0,0,0.2);min-width: 300px;">
          {{ address }}
        </div>
        <lbtn type="text" @click="help">帮助</lbtn>
        <lbtn type="text" @click="gpback">退货汇总</lbtn>

        <gpback ref="gpbackRef" @close="closedPop"  />
      </el-space>
    </div>
    <div style="margin-top: 20px;">
      <el-card  shadow="never" style="height: calc(100vh - 130px);" body-style="padding: 10px 0px;">
        <template #header>
          <div style="display: flex;">
            <div style="flex: 1;">退货商品列表</div>
            <div style="font-size: 20px;font-weight: bold;color: #515A6E;padding-top: 10px;border-bottom: 1px solid rgba(0,0,0,0.3);margin-right: 50px;padding-right: 10px;">
              原票据金额￥：<span style="color: #c45656;">{{arrearsReal}}</span>
            </div>
            <div style="font-size: 20px;font-weight: bold;color: #515A6E;padding-top: 10px;border-bottom: 1px solid rgba(0,0,0,0.3);margin-right: 50px;padding-right: 10px;">
              退包装物￥：<span style="color: #c45656;">{{totalAmount}}</span>
            </div>
            <div style="font-size: 20px;font-weight: bold;color: #515A6E;padding-top: 10px;border-bottom: 1px solid rgba(0,0,0,0.3);margin-right: 50px;padding-right: 10px;">
              结余金额￥：<span style="color: #c45656;">{{leftAmount}}</span>
            </div>
            <div>
              <lbtn type="primary" size="medium" @click="confirm">保存并审核</lbtn>
            </div>
            <div style="margin-left: 30px;">
<!--              <lbtn   size="medium" @click="clear">清空</lbtn>-->
            </div>
          </div>
        </template>
        <t-grid  size="large" v-if="buId" :data-list="backList" :fields="columns" @editClosed="editClose" @cellClick="cellClick" />
        <el-empty v-if="!buId" description="扫描二维码"></el-empty>
      </el-card>
    </div>
    <el-dialog v-model="showPop" title="修改单位" :z-index="9" :width="300">
      <tiny-select v-model="unit" placeholder="请选择" size="large" @change="changeUnit">
        <tiny-option v-for="(item, index) in units" :key="index" :label="item.name" :value="item.id"> </tiny-option>
      </tiny-select>
    </el-dialog>
    <el-dialog v-model="helpPop" draggable title="本页帮助说明">
      <el-image src="https://download.sanzhiyun.cn/web5/help/%E9%80%80%E5%8C%85%E8%A3%85%E7%89%A9.png"></el-image>
    </el-dialog>
  </div>
</template>
<script>
// 退包装物品
import tool from "@/utils/tool";
import bus from "@/store/bus.js";
import { Select, Option,   } from '@opentiny/vue'
import Gpback from "./gpback.vue";

export default {
  name: "wrapperBack",
  components: {
    Gpback,
    TinySelect: Select,
    TinyOption: Option,
  },
  data () {
    return {
      billDate: tool.getDay(),
      locationId: null,
      locationName: null,
      buId: null,
      buName: '',
      address: '',
      code: '',
      backList: [],
      helpPop: false,
      showPop: false,
      columns:[
        {type: 'index', width: 50},
        {field: 'name', title: '商品名称', width: 300,align: 'left'},
        {field: 'locationName', title: '仓库', width: 80},
        {field: 'specs', title: '规格', width: 80},
        {field: 'unit', title: '单位', width: 80},
        {field: 'qty', title: '数量', width: 110,editor: {component: 'input',attrs:{type:'number'}, autoselect: true,},},
        {field: 'price', title: '单价', width: 110,editor: {component: 'input',attrs:{type:'number'}, autoselect: true}},
        {field: 'amount', title: '金额', width: 110,editor: {component: 'input',attrs:{type:'number'}, autoselect: true}},
        {field: 'remark', title: '备注', width: 110,editor: {component: 'input', autoselect: true}},
      ],
      currentRow: {},
      units: [],
      unit: '',
      billId: '',
      arrearsReal: '0.00', // 原票据金额
      popOpened: false
    }
  },
  created() {
    bus.$on('scan-ret', this.scanRet)
  },
  unmounted () {
    bus.$off('scan-ret', this.scanRet)
  },
  computed: {
    totalAmount () {
      return tool.xe.toFixed(tool.xe.sum(this.backList, 'amount'),2)
    },
    tuiList () {
      return this.backList.filter(row => {
        return tool.xe.toNumber(row.qty) > 0
      })
    },
    leftAmount () {
      return tool.xe.toFixed(tool.xe.subtract(this.arrearsReal, this.totalAmount), 2)
    }
  },
  methods: {
    closedPop () {
      this.popOpened = false
    },
    help () {
      this.helpPop = true
    },
    gpback () {
      this.popOpened = true
      this.$refs.gpbackRef.open()
    },
    doSearch () {
      let code = '150601-567701'
      let arr = code ? code.split('-') : []
      if (arr.length !== 2) {
        return tool.err('二码码识别错误，请重试')
      }
      this.scanRet({code})
    },
    cellClick (cell) {
      if(cell.column.property === 'unit') {
        this.showPop = true
        this.currentRow = cell.row
        this.unit = cell.row.unit
        this.units = []
        this.units.push({id: cell.row.unit1, name: cell.row.unit1})
        if(cell.row.unit2)
          this.units.push({id: cell.row.unit2, name: cell.row.unit2})
      }
    },
    changeUnit (val) {
      this.currentRow.unit = val
      this.showPop = false
    },
    scanRet ({ code }) {
      let arr = code ? code.split('-') : []
      if (arr.length !== 2) {
        return tool.err('二维码识别错误，请重试')
      }
      if(this.popOpened) {
        // 弹出汇总小票
        tool.post('deliver/getBackRel', {billId: arr[1]}, true).then(ret => {
          this.$refs.gpbackRef.addData(ret.data)
        })
      }
      else {
        this.billId = arr[1]
        this.code = code
        this.getList()
      }
    },
    getList () {
      tool.post('deliver/backList', {code: this.code}, true).then(ret => {
        if(ret.stat) {
          this.locationId = ret.data.locationId
          this.locationName = ret.data.locationName
          this.buId = ret.data.buId
          this.buName = ret.data.buName
          this.address = ret.data.address
          this.arrearsReal = tool.xe.toFixed(ret.data.arrearsReal,2)
          this.backList = ret.data.list
        }
      })
    },
    editClose (cell) {
      let row = cell.row
      let field = cell.column.property
      if(field === 'qty') {
        row.qty = Math.abs(tool.xe.toNumber(row.qty))
        row.amount = tool.xe.toFixed(tool.xe.multiply(row.qty, row.price), 2)
      }
      if(field === 'price') {
        row.price = Math.abs(tool.xe.toNumber(row.price))
        row.amount = tool.xe.toFixed(tool.xe.multiply(row.qty, row.price), 2)
      }
      if(field === 'amount') {
        row.amount = Math.abs(tool.xe.toNumber(row.amount))
        if(tool.xe.toNumber(row.qty)) {
          row.price = tool.xe.toFixed(tool.xe.divide(row.amount, row.qty), 2)
        }
        else {
          row.amount = 0
        }
      }
    },
    confirm () {
      let list = []
      this.tuiList.map(row => {
        list.push({
          invId: row.id,
          invName: row.name,
          locationId: this.locationId,
          locationName: this.locationName,
          spec: row.spec,
          calNum: row.unit === row.unit1 ? row.spec:1,
          unit: row.unit,
          price: row.price,
          amount: row.amount,
          remark: row.remark,
          qty: row.qty,
        })
      })
      if(list.length === 0) return tool.warning('请输入要退货的商品数量')
      if(!this.locationId) return tool.warning('没有设置仓库')
      let invoice = {
        buId: this.buId,
        oldBillId: this.billId,
        buName: this.buName,
        billDate: this.billDate,
        transType: 150602,
        transTypeName: '销售退货单',
        billType: 'SALE',
        totalAmount: tool.xe.sum(list, 'amount'),
        amount: tool.xe.sum(list, 'amount'),
        arrears: tool.xe.sum(list, 'amount'),
        orgin: 'ps',
        infos: list
      }
      tool.post('deliver/billHasBack', {billId: this.billId}).then(ret => {
        if(ret.stat) {
          if(ret.msg) {
            tool.confirm(ret.msg, '保存提示').then(() => {
              tool.post('bill/saveBack', invoice, true).then(ret => {
                if(ret.stat) {
                  tool.post('bill/toAccounted', {transType: 150602,ids: [ret.data.id]}).then(ret => {
                    if(ret.stat) {
                      this.clear()
                    }
                  })
                }
              })
            })
          }
          else {
            tool.post('bill/saveBack', invoice, true).then(ret => {
              if(ret.stat) {
                tool.post('bill/toAccounted', {transType: 150602,ids: [ret.data.id]}).then(ret => {
                  if(ret.stat) {
                    this.clear()
                  }
                })
              }
            })
          }
        }
      })
    },
    clear () {
      this.billDate =  tool.getDay()
      this.buId = null
      this.billId = null
      this.buName =  ''
      this.address =  ''
      this.locationId =  ''
      this.locationName =  ''
      this.backList = []
    }
  }
}
</script>
<style scoped lang="scss">
.title {
  text-align: center;
  font-weight: bold;
  font-size: 22px;
  background-color: #01aaee;
  color: white;
  height: 40px;
  line-height: 40px;
}
</style>